# -*- coding: utf-8 -*-
from django.shortcuts import render_to_response, get_object_or_404, redirect
from getdebt.main.models import Contragent, Firm, Individual, Debt, Status
from getdebt.profile.views import user_can_add, user_can_view, userinfo
from django.template import RequestContext
from getdebt.advice.views import advices
from getdebt.main.views import alf, abc_filter, obj_model_html
from django.contrib.auth.decorators import user_passes_test
from forms import FirmForm, IndividualForm, DebtForm, VidForm, YesnoForm
from django.db.models.options import Options
import datetime
from django.core.urlresolvers import reverse

def confirm(request):
    # удаление организации или физлица!!!
    req=request
    dictionary={}
    form = YesnoForm()
    dictionary['form']=form
    return render_to_response('forms/form.tpl', dictionary, 
                              context_instance=RequestContext(request, processors=[userinfo]))

@user_passes_test(user_can_add, login_url="/login/")
def contragent(request, vid, status, page):
    # добавление или редактирование организации или физлица!!!
    dictionary={}
    adv_list = []
    if 'firm' in vid:
        contragent = FirmForm
        contr = Firm
    else:
        contragent = IndividualForm
        contr = Individual
    if 'debtor' in status:
        dictionary['header'] = u'Информация о должнике'
    else:
        dictionary['header'] = u'Информация о кредиторе'
    status = get_object_or_404(Status,code = status)
    dictionary['page']=page
    dictionary['status']=status
    if request.method == 'POST':
        if page=='new':
            form = contragent(request.POST)
        else:
            c = contr.objects.get(pk=page)
            form = contragent(request.POST, instance = c)    
        if form.is_valid():
            redirect_to = request.POST['redirect_to']
            new_contr = form.save(commit=False)
            new_contr.user=request.user
            new_contr.status = status
            new_contr.rec_date = datetime.datetime.now()
            new_contr.save()
            if not redirect_to or '//' in redirect_to or ' ' in redirect_to:
                redirect_to = '/html/thanks/'
            return redirect(redirect_to)
    else:
        if page=='new':
            form = contragent()
            adv_list = advices(request, 'new_firm')
        else:
            try:
                c = contr.objects.get(pk=page)
            except:
                return redirect('/html/404/')
            form = contragent(instance=c)
            #form = contragent(initial=c.__dict__)
            adv_list = advices(request, 'exist_firm')
    dictionary['form']=form
    dictionary['advices_list'] = adv_list
    return render_to_response('forms/form.tpl', dictionary, 
        context_instance=RequestContext(request, processors=[userinfo]))

@user_passes_test(user_can_add, login_url="/login/")
def view_contragent(request, vid, page):
    # добавление или редактирование организации или физлица!!!
    dictionary={}
    if 'firm' in vid:
        contr = Firm
    else:
        contr = Individual

    try:
        c = contr.objects.get(pk=page)
    except:
        return redirect('/html/404/')
    else:
        status = c.status.code
        idstr = str(c.id)
  
    #-------------------------------------------------------------------------удаление редактирование объекта    
    if request.method == 'POST':
        try:
            index = request.POST['index']
        except:
            index=-1      
        if index=='0':
            return confirm(request)
        elif index=='1':
            tup = vid, status, idstr , status
            return redirect('/contragent/%s/%s/%s/?next=/mycontragents/%s/' % tup)
        try:
            yes = request.POST['yesno']
        except:
            yes=''      
        if yes:
            c.delete()
            return redirect('/mycontragents/%s/' % status)
    #----------------------------------------------------------------------------------------------------    
    
    dictionary['contragent']=obj_model_html(c,['user_id','rec_date','id','contragent_ptr','user'])
    dictionary['obj_contragent'] = c
    dictionary['object_list'] = c
    dictionary['vid']=vid
    return render_to_response('view_contragent.tpl', dictionary, 
        context_instance=RequestContext(request, processors=[userinfo]))

@user_passes_test(user_can_add, login_url="/login/")
def addcontr(request, status):
    # форма выбора организации или физлица и переход на добавление, соответственно, организации или физлица
    dictionary={}
    if 'debtor' in status:
        dictionary['header']='Добавить должника'
    else:
        dictionary['header']='Добавить кредитора'
    adv_list = advices(request, 'exist_firm')
    if request.method == 'POST':
        form = VidForm(request.POST)
        if form.is_valid():
            vid = form.cleaned_data['vid']
            tup = vid, status, status
            return redirect('/contragent/%s/%s/new/?next=/mycontragents/%s/' % tup)
    else:
        form = VidForm()
    dictionary['form']=form
    dictionary['advices_list'] = adv_list
    return render_to_response('forms/form.tpl', dictionary, 
        context_instance=RequestContext(request, processors=[userinfo]))

@user_passes_test(user_can_add, login_url="/login/")
def mycontragents(request, status):
    #форма списка своих контрагентов, должников и кредиторов
    dictionary = {}
    dictionary['status'] = status
    st = get_object_or_404(Status,code__exact = status)
    dictionary['ext_tpl']='main-1col.tpl'
    
    #------------------------------------------------------------------------------------сортировка
    srtf = request.REQUEST.get('sortf', 'id')
    srti = request.REQUEST.get('sorti', 'id')
    try:
        f = Firm._meta.get_field_by_name(srtf)
    except:
        srtf='id'
    firms = Firm.objects.filter(user = request.user, status = st).order_by(srtf)
    try:
        f = Individual._meta.get_field_by_name(srti)
    except:
        srti='id'
    individuals = Individual.objects.filter(user = request.user, status = st).order_by(srti)
    #---------------------------------------------------------------------------------------------------        
    
    #-------------------------------------------------------------------фильтр по первой букве алфавита
    posabc = request.REQUEST.get('abc', '')    
    if posabc:
        firms = abc_filter(firms,'name',posabc)
        individuals = abc_filter(individuals, 'fio',posabc)
    #---------------------------------------------------------------------------------------------------
    
    #-------------------------------------------------------------------------удаление добавление объектов    
    if request.method == 'POST':
        qd=request.POST
        try:
            index = qd['index']
            contrs=qd.getlist('_selected_action')
        except:
            index=-1
            contrs=[]
            
        if index=='0' and contrs: #-----------------------------------------если нажали Удалить
            for cc in contrs:
               c = Contragent.objects.filter(pk=cc)
               c.delete()
               return redirect('/mycontragents/%s/' % status)
        elif index=='1':#-----------------------------------------если нажали Добавить организацию
            tup = 'firm', status, status
            return redirect('/contragent/%s/%s/new/?next=/mycontragents/%s/' % tup)
        elif index=='2':#-----------------------------------------если нажали Добавить физлицо
            tup = 'individual', status, status
            return redirect('/contragent/%s/%s/new/?next=/mycontragents/%s/' % tup)

    #----------------------------------------------------------------------------------------------------    
    
    dictionary['firms'] = firms
    dictionary['individuals'] = individuals
    dictionary['advices_list'] = advices(request, 'my_contragents')
    return render_to_response('mycontragents.tpl', dictionary,
        context_instance=RequestContext(request, processors=[alf, userinfo]))

@user_passes_test(user_can_add, login_url="/login/")
def adddebt(request):
    # форма добавления долга
    dictionary={}
    adv_list = advices(request, 'add_debt')
    if request.method == 'POST':
        form = DebtForm(request.POST,user=request.user)
        if form.is_valid():
            agree=form.cleaned_data['agree']
            if not agree:
                dictionary['errors']=True
                dictionary['texterror'] = u'Вам необходимо подтвердить, что Вы ознакомлены и согласны с условиями пользовательского соглашения'
            else:
                new_debt = form.save(commit=False)
                new_debt.rec_date = datetime.datetime.now()
                new_debt.user = request.user
                try:
                    new_debt.save()
                except:
                    dictionary['errors']=True
                    dictionary['texterror'] = u'Непредвиденная ошибка записи'
                return redirect('/html/thanks/')
    else:
        form = DebtForm(user=request.user)
    dictionary['form']=form
    dictionary['advices_list'] = adv_list
    return render_to_response('forms/form.tpl', dictionary, 
        context_instance=RequestContext(request, processors=[userinfo]))


@user_passes_test(user_can_add, login_url="/login/")
def debt(request, page):
    # добавление или редактирование организации или физлица!!!
    dictionary={}
    adv_list = []    
    dictionary['page']=page
    if request.method == 'POST':
        if page=='new':
            form = DebtForm(request.POST,user=request.user)
        else:
            d = Debt.objects.get(pk=page)
            form = DebtForm(request.POST, user=request.user, instance = d)    
        if form.is_valid():
            redirect_to = request.POST['redirect_to']
            agree=form.cleaned_data['agree']
            if not agree:
                dictionary['errors']=True
                dictionary['texterror'] = u'Вам необходимо подтвердить, что Вы ознакомлены и согласны с условиями пользовательского соглашения'
            else:
                new_debt = form.save(commit=False)
                new_debt.rec_date = datetime.datetime.now()
                new_debt.user = request.user
                try:
                    new_debt.save()
                except:
                    dictionary['errors']=True
                    dictionary['texterror'] = u'Непредвиденная ошибка записи'
                if not redirect_to or '//' in redirect_to or ' ' in redirect_to:
                    redirect_to = '/html/thanks/'
                return redirect(redirect_to)
    else:
        if page=='new':
            form = DebtForm(user=request.user)
            adv_list = advices(request, 'new_debt')
        else:
            try:
                d = Debt.objects.get(pk=page)
            except:
                return redirect('/html/404/')
            form = DebtForm(user=request.user, instance=d)
            adv_list = advices(request, 'exist_debt')
    dictionary['form']=form
    dictionary['advices_list'] = adv_list
    return render_to_response('forms/form.tpl', dictionary, 
        context_instance=RequestContext(request, processors=[userinfo]))

@user_passes_test(user_can_add, login_url="/login/")
def mydebts(request):
    #форма списка своих контрагентов, должников и кредиторов
    dictionary = {}
    dictionary['ext_tpl']='main-1col.tpl'
    
    #------------------------------------------------------------------------------------сортировка
    srt = request.REQUEST.get('sort', 'id')
    try:
        f = Debt._meta.get_field_by_name(srt)
    except:
        srt='id'
    debts = Debt.objects.filter(user = request.user).order_by(srt)
    #---------------------------------------------------------------------------------------------------        
    
    #-------------------------------------------------------------------------удаление добавление объектов    
    if request.method == 'POST':
        qd=request.POST
        try:
            index = qd['index']
            dbs=qd.getlist('_selected_action')
        except:
            index=-1
            dbs=[]
        if index=='0' and dbs: #-----------------------------------------если нажали Удалить
            for dd in dbs:
               d = Debt.objects.filter(pk=dd)
               d.delete()
            return redirect('/mydebts/')
        elif index=='1':#-----------------------------------------если нажали Добавить организацию
            return redirect('/debt/new/?next=/mydebts/')
    #----------------------------------------------------------------------------------------------------    
    
    dictionary['debts'] = debts
    dictionary['advices_list'] = advices(request, 'my_contragents')
    return render_to_response('mydebts.tpl', dictionary,
        context_instance=RequestContext(request, processors=[userinfo]))